import nme.Lib;
import nme.Assets;
import nme.display.Graphics;
import nme.display.Sprite;
import nme.display.Bitmap;
import nme.display.BitmapData;

import nme.geom.Rectangle;
import nme.geom.Matrix;
import nme.geom.Point;

import nme.events.Event;
import nme.events.MouseEvent;
import nme.events.KeyboardEvent;
import nme.Lib;

class Loading extends Sprite implements IGameState
{
	public var _substate:SubState;
	public var _resourceRequest:Int;
	
	private var _loadingBarBg:DumpObj;
	private var _loadingBar:DumpObj;
	private var _loadingLabel:Label;
	
	public function new ()
	{
		super ();
		var screenWidth:Int = Lib.current.stage.stageWidth;
		var screenHeight:Int = Lib.current.stage.stageHeight;
		
		addChild (new DumpObj (0, 0, 0, 0, screenWidth, screenHeight, 0x000000, 0x000000, 1));
		
		var loadbarX:Int = screenWidth >> 1;
		var loadbarY:Int = (screenHeight >> 2) * 3;
		var loadbarWidth:Int = screenWidth - 100;
		trace ("loadbarWidth: " + loadbarWidth);
		addChild (_loadingBarBg = new DumpObj (loadbarX, loadbarY, -loadbarWidth >> 1, -10, loadbarWidth, 20, 0xFFFFFF, 0x000000, 1));
		addChild (_loadingBar = new DumpObj (loadbarX, loadbarY, -loadbarWidth + 4 >> 1, -8, 10, 16, 0x000000, 0x000000, 1));
		
		_loadingLabel = Label.create ("LOADING ... 0", Fonts.DETAIL_WHITE_20, Anchor.TOP_CENTER);
		_loadingLabel.x = loadbarX;
		_loadingLabel.y = loadbarY + 20;
		// _loadingBar.alpha = 0.5;
		addChild (_loadingLabel);
		
		_substate = SubState.LOADING_STATE;
	}
	
	public function getSubstate ():SubState
	{
		return _substate;
	}
	
	var process:Int = 0;
	var maxprocess:Int = 1;
	
	public function loading ():Void
	{
		process++;
		
		_loadingBar.setWidth (process / maxprocess * (_loadingBarBg.width - 5));
		_loadingBar.render ();
		_loadingLabel.setText ("LOADING ... " + process);
	}
	
	public function loadingCompleted ():Bool
	{
		return process >= maxprocess;
	}
	
	public function init ():Void
	{
		_substate = SubState.DESTROY_STATE;// SubState.LOOP_STATE;
		_loadingLabel.setText ("PRESS ANY KEYS TO CONTINUE");
		
		Lib.current.stage.addEventListener (KeyboardEvent.KEY_DOWN, onkeyboard);
	}

	public function loop ():Void
	{
		_loadingLabel.alpha -= 0.01;
		
		if (_loadingLabel.alpha <= 0) _loadingLabel.alpha = 1;
	}
	
	private function onkeyboard (e:KeyboardEvent):Void
	{
		_substate = SubState.DESTROY_STATE;
	}
	
	public function destroy ():Void
	{
		Lib.current.stage.removeEventListener (KeyboardEvent.KEY_DOWN, onkeyboard);
	}
}